import React, {PropsWithChildren, useEffect, useState} from "react"
import ActionsDrawerLayout from "../components/ActionsDrawerLayout";
import {DrawerProps, Form} from "antd";
import {FormInstance} from "antd/es/form/hooks/useForm";

export interface FormDrawerProps<Values> {
    open: boolean
    title: string
    onClose: () => void
    onConfirm: (values: Values) => Promise<unknown>
    initialValues?: Values
    onBeforeConfirm?: () => void
    form?: FormInstance
    afterOpenChange?:DrawerProps["afterOpenChange"]
}

function FormDrawer<Values = any>({
                                      open,
                                      title,
                                      onClose,
                                      onConfirm,
                                      children,
                                      initialValues,
                                      onBeforeConfirm,
                                      form,afterOpenChange
                                  }: PropsWithChildren<FormDrawerProps<Values>>) {
    const [loading, setLoading] = useState(false)
    let [myFrom] = Form.useForm();
    let formInstance = form ?? myFrom
    return (
        <ActionsDrawerLayout afterOpenChange={(open)=>{
            if (open && initialValues){
                formInstance.setFieldsValue(initialValues)
            }
            if (!open) {
                formInstance.resetFields()
            }
        }} confirmLoading={loading} onClose={() => {
            onClose()
        }} open={open} onConfirm={() => {
            onBeforeConfirm && onBeforeConfirm()
            formInstance.submit()
        }} title={title}>
            <Form<Values> layout={"vertical"} form={formInstance} onFinish={values => {
                setLoading(true)
                onConfirm(values).finally(() => {
                    setLoading(false)
                })
            }}>
                {children}
            </Form>
        </ActionsDrawerLayout>
    )
}

export default FormDrawer
